<template>
  <div class="container">
    <a-card style="width: 100%">
      <div class="filter">
        <div class="form">
          <a-form layout="inline" :model="searchPayload">
            <a-form-item label="名称搜索">
              <a-input v-model:value="searchPayload.chinese_name" placeholder="请输入" />
            </a-form-item>
          </a-form>
        </div>
        <div class="action-btns">
          <a-space>
            <a-button type="primary" @click="getPlantMedicinalList">查询</a-button>
            <a-button v-permission="['管理者', '老师']" @click="openAddPage()">新增</a-button>
            <a-upload
              :file-list="[]"
              name="file"
              :data="{ area: area }"
              :beforeUpload="fileBeforeUpload"
              :on-success="fileUploadSuccess"
              :on-error="fileUploadError"
              :itemRender="null"
              :action="importAction"
            >
              <a-button v-permission="['管理者', '老师']" :loading="uploading">导入</a-button>
            </a-upload>
            <a-button v-permission="['管理者', '老师']" @click="downloadTemp">下载模板</a-button>
          </a-space>
        </div>
      </div>
    </a-card>
    <div class="content">
      <a-card style="width: 100%">
        <a-table
          :dataSource="plantMedicinalList"
          :columns="columns"
          :pagination="{
            onChange: handlePageChange,
            total: pageInfo.total,
            pageSize: pageInfo.pageSize
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'img_url'">
              <a-image
                :width="88"
                :height="88"
                fallback=""
                :src="getShowImage(record.hand_painted_url)"
              />
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button type="link" @click="openDetailPage(record.id)">查看</a-button>
                <a-button v-permission="['管理者']" type="link" @click="openAddPage(record.id)"
                  >编辑</a-button
                >
                <a-popconfirm
                  title="确定删除？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="del(record.id)"
                >
                  <a-button v-permission="['管理者', '老师']" type="link" danger>删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { fetchPlantDelete, fetchPlantList, fetchPlantTemp } from '@/api/plant'
import { message } from 'ant-design-vue'

const router = useRouter()
const area = ref(2) // 0、所有 1、理论教材学习植物 2、金佛山野外救生植物 3、校园救生植物 4西南地区救生植物
const searchPayload = ref({
  chinese_name: ''
})
const pageInfo = ref({
  page: 1,
  pageSize: 10,
  total: 0
})
onMounted(() => {
  getPlantMedicinalList()
})
const getPlantMedicinalList = async () => {
  const params = {
    page_num: pageInfo.value.page,
    conditions: [
      {
        key: 'chinese_name',
        operator: 'like',
        value: searchPayload.value.chinese_name
      },
      {
        key: 'area',
        operator: 'eq',
        value: area.value
      }
    ],
    page_size: pageInfo.value.pageSize,
    order_info: {
      key: 'create_time',
      order: 'desc'
    }
  }
  const res = await fetchPlantList(params)
  plantMedicinalList.value = res.data.data
  pageInfo.value.total = res.data.paging.total
}
const plantMedicinalList = ref<any[]>([])
const columns = [
  {
    title: '序号',
    align: 'center',
    dataIndex: 'number',
    key: 'number'
  },
  {
    title: '图片',
    align: 'center',
    dataIndex: 'img_url',
    key: 'img_url'
  },
  {
    title: '植物名称',
    align: 'center',
    dataIndex: 'chinese_name',
    key: 'chinese_name'
  },
  {
    title: '分布位置',
    align: 'center',
    dataIndex: 'geographical',
    key: 'geographical',
    width: 240
  },
  {
    title: '拉丁学名',
    align: 'center',
    dataIndex: 'latin_name',
    key: 'latin_name'
  },
  {
    title: '别名',
    align: 'center',
    dataIndex: 'alias',
    key: 'alias'
  },
  {
    title: '药材名',
    align: 'center',
    dataIndex: 'medicinal_name',
    key: 'medicinal_name'
  },
  {
    title: '操作',
    align: 'center',
    width: '120px',
    dataIndex: 'action',
    key: 'action'
  }
]

const getShowImage = computed(() => {
  return (urls: string) => {
    if (urls) {
      return urls.split(',')[0]
    }
    return ''
  }
})

const handlePageChange = (page: number, pageSize: number) => {
  pageInfo.value.page = page
  pageInfo.value.pageSize = pageSize
  getPlantMedicinalList()
}

const del = async (id: any) => {
  const res = await fetchPlantDelete(id)
  if (res.status === 200) {
    await getPlantMedicinalList()
    message.success('删除成功')
  }
}

const openAddPage = (id?: string) => {
  router.push({
    path: '/plant/add',
    query: { id, area: area.value }
  })
}
const openDetailPage = (id: string) => {
  router.push({
    path: '/plant/detail',
    query: { id, type: 'jinfo' }
  })
}
const downloadTemp = () => {
  fetchPlantTemp()
}
const importAction = `${import.meta.env.VITE_BASE_URL}/plant/plant-info/uploadPlantInfo`
const uploading = ref(false)
const fileBeforeUpload = () => {
  uploading.value = true
}
const fileUploadSuccess = () => {
  uploading.value = false
  message.success('上传成功')
  getPlantMedicinalList()
}
const fileUploadError = () => {
  uploading.value = false
  message.error('上传失败，请重试')
}
</script>

<style scoped lang="scss">
.container {
  .filter {
    display: flex;
    justify-content: space-between;
  }

  .content {
    margin-top: 24px;
  }
}
</style>
